package com.example.demo.utils.token;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.pojo.Token;
import com.example.demo.utils.Base64Util;
import com.example.demo.utils.MD5Util;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * token(放请求头里面) 为json格式后面加 验证码(base64)
 * 验签 MD5 有损格式加密 不可逆
 * 1 -->(MD5) 固定字符
 * MD5验证
 * <p>
 * 所有请求来之前做(除登录)
 * token里有 一个唯一id 数据
 * <p>
 * 每一次请求 token会换 替换旧的 给予新的
 */
@Component
public class TokenUtil {


    /**
     * 生成Token字符串
     *
     * @param token
     * @return {"exTime":1641636380319,"id":1,"type":2;4240656e51f58cc51bc6133ec9cf23c7}
     */
    public static String createNewTokenAndMD5(Token token) {
        //将token对象转换为md5加密的串
        String s = JSON.toJSONString(token);
        String md5 = MD5Util.getMd5(s);
        return createTokenBase64(md5, s);
    }


    /**
     * 将token对象转换为md5加密的串
     * token --> f66bb9c5d96dea476ef075ae09cd5af5（32位）
     *
     * @param token
     * @return
     */
    public static String createTokenMD5(Token token) {
        String s = JSON.toJSONString(token);
        return MD5Util.getMd5(s);
    }

    /**
     * 将md5加密的串和加密前的串组合
     * {"exTime":123,"id":1,"type":1;f66bb9c5d96dea476ef075ae09cd5af5}
     *
     * @param md5   f66bb9c5d96dea476ef075ae09cd5af5
     * @param token {"exTime":123,"id":1,"type":1}
     * @return {"exTime":1641628697267,"id":1,"type":2;f66bb9c5d96dea476ef075ae09cd5af5}
     */
    private static String createTokenBase64(String md5, String token) {
        StringBuffer sb = new StringBuffer(token);
        String a = new StringBuffer(md5).insert(0, ';').toString();
        sb.insert(sb.length() - 1, a);
        return sb.toString();
    }

    /**
     * 将token对象转换为最终base64编码
     *
     * @param token
     * @return
     */
    public static String createNewTokenBytoken(Token token) {
        //token --> f66bb9c5d96dea476ef075ae09cd5af5（32位）
        String tokenMD5 = TokenUtil.createTokenMD5(token);
        String tokenString = TokenUtil.createTokenBase64(tokenMD5, JSON.toJSONString(token));
        return Base64Util.switchToBase64(tokenString);
    }


    //验证token方法

    /**
     * 验证当前token
     * 拆分token 前后验证
     *
     * @param tokenBase64
     * @return
     */
    public static boolean checkToken(String tokenBase64) {
        if (tokenBase64 == "Token错误" || tokenBase64.equals("Token错误")) {
            return false;
        }
        StringBuilder sb = new StringBuilder(Base64Util.reversalBase64(tokenBase64));

        String substring;
        StringBuffer tokenString;
        StringBuffer append;
        try {
            //后面的
            //f6fdf5d2c04b61c7353ad1b56ac96dc9
            substring = sb.substring(sb.length() - 34);
            tokenString = new StringBuffer(substring).delete(substring.length() - 1, substring.length()).delete(0, 1);

            //前面的
            //{"exTime":1641781630574,"id":1,"type":2}
            String substring2 = sb.substring(0, sb.length() - 34);
            append = new StringBuffer(substring2).append('}');
        } catch (Exception e) {
            return false;
        }

        //token字符串转换为Token对象
        Token token1;
        try {
            token1 = JSON.parseObject(append.toString(), Token.class);
        } catch (Exception e) {
            return false;
        }
        String tokenMD5 = createTokenMD5(token1);
        return tokenString.toString().equals(tokenMD5);

    }


    /**
     * 检验token是否超时
     *
     * @param token 原串
     * @return
     */
    public static Boolean checkOverTime(String token) {
        StringBuffer sb = new StringBuffer(Base64Util.reversalBase64(token));

        //前面的
        //{"exTime":1641781630574,"id":1,"type":2}
        String substring2 = sb.substring(0, sb.length() - 34);
        StringBuffer append = new StringBuffer(substring2).append('}');

        Token token1 = JSON.parseObject(append.toString(), Token.class);
        //拿token与当前时间比较
        if (token1.getExTime() < System.currentTimeMillis()) {
            return false;
        }
        return true;
    }

    /**
     * 将原来的Token转化为新的Token(更新时间)
     *
     * @param token
     * @return
     */
    public static String createNewToken(String token) {
        StringBuffer sb = new StringBuffer(Base64Util.reversalBase64(token));

        //前面的
        //{"exTime":1641781630574,"id":1,"type":2}
        String substring2 = sb.substring(0, sb.length() - 34);
        StringBuffer append = new StringBuffer(substring2).append('}');

        Token token1 = JSON.parseObject(append.toString(), Token.class);

        Long time = System.currentTimeMillis() + 100 * 60 * 30;

        long time1 = new Date(time).getTime();

        token1.setExTime(time1);
        return createNewTokenBytoken(token1);
    }


    /**
     * 获取id
     *
     * @param token
     * @return
     */
    public static String getId(String token) {
        StringBuffer sb = new StringBuffer(Base64Util.reversalBase64(token));
        //前面的
        //{"exTime":1641781630574,"id":1,"type":2}
        String substring2 = sb.substring(0, sb.length() - 34);
        substring2 = substring2 + "}";
        JSONObject jsonObject = JSONObject.parseObject(substring2);
        return jsonObject.getString("id");
    }
}
